#
# by lalawue, 2021/05/25

.PHONY : all
.PHONY : test
.PHONY : out
.PHONY : install
.PHONY : uninstall

NAME=moocscript
WSRC=web
SUFX=mooc
ODIR=out/$(NAME)
WDIR=out/$(WSRC)
CS=./bin/$(NAME)

#
# edit path before install

# bin/$(NAME)
INSTALL_BIN_PATH=/usr/local/bin
# Lua/LuaJIT interpreter
INSTALL_LUA_EXEC=/usr/local/bin/lua
# for store $(NAME) core *.lua
INSTALL_LUA_PATH=/usr/local/opt/$(NAME)

all:
	@echo "Usage:"
	@echo "\t $ make test \t# busted ./$(NAME)/?.lua"
	@echo "\t $ make out \t# busted ./$(ODIR)/?.lua"
	@echo "\t $ make web \t# busted ./$(WDIR)/moocscript-web.lua"
	@echo "\t $ make gen \t# generate ./$(ODIR)/?.lua from ./$(NAME)/?.mooc"
	@echo "\t $ make install \t# please edit Makefile first"
	@echo "\t $ make uninstall \t# please edit Makefile first"

test: bridge_out
	rm -f *.out && rm -rf out/
	echo 'package.path="./?.lua" -- auto generated by Makefile' > spec/aaa_spec.lua
	busted

out: gen bridge_out
	echo 'package.path="./out/?.lua" -- auto generated by Makefile' > spec/aaa_spec.lua
	mkdir -p out/spec
	cp spec/_tool_bridge.lua out/spec/
	busted

web: gen bridge_web
	echo 'package.path="./out/?.lua" -- auto generated by Makefile' > spec/aaa_spec.lua
	mkdir -p out/spec
	cp spec/_tool_bridge.lua out/spec/
	busted

gen:
	rm -f *.out && rm -rf out/
	mkdir -p $(ODIR)
	mkdir -p $(WDIR)
	$(CS) -s $(NAME)/compiler.$(SUFX) > $(ODIR)/compiler.lua
	$(CS) -s $(NAME)/core.$(SUFX) > $(ODIR)/core.lua
	$(CS) -s $(NAME)/parser.$(SUFX) > $(ODIR)/parser.lua
	$(CS) -s $(NAME)/utils.$(SUFX) > $(ODIR)/utils.lua
	$(CS) -s $(NAME)/class.$(SUFX) > $(ODIR)/class.lua
	$(CS) -s $(NAME)/repl.$(SUFX) > $(ODIR)/repl.lua
	$(CS) $(WSRC)/web_gen_lua.$(SUFX) > $(WDIR)/moocscript-web.lua
	$(CS) $(WSRC)/web_gen_js.$(SUFX) $(WSRC)/web_template.js $(WDIR)/moocscript-web.lua > $(WDIR)/moocscript-web.js

bridge_out:
	echo 'return { parser = require("moocscript.parser"), compiler = require("moocscript.compiler") }' > spec/_tool_bridge.lua

bridge_web:
	echo 'return { parser = require("web.moocscript-web").parser, compiler = require("web.moocscript-web").compiler }' > spec/_tool_bridge.lua

MN_DIR=$(INSTALL_LUA_PATH)/$(NAME)/
MN_BIN=$(INSTALL_BIN_PATH)/$(NAME)

install:
	@echo 'Please edit Makefile first !!!'
#	rm -rf $(MN_DIR)
#	mkdir -p $(MN_DIR)
#	echo "#!$(INSTALL_LUA_EXEC)\n" > $(MN_BIN)
#	echo "package.path = package.path .. \";$(INSTALL_LUA_PATH)/?.lua;\"" >> $(MN_BIN)
#	cat bin/$(NAME) | grep -v '#!' >> $(MN_BIN)
#	cp -a $(NAME)/*.lua $(MN_DIR)
#	chmod +x $(MN_BIN)

uninstall:
	@echo 'Please edit Makefile first !!!'
#	rm -f $(MN_BIN)
#	rm -rf $(MN_DIR)

clean:
	rm -f *.out
	rm -rf out/